import datetime
import json
import random
import sys
from utils.mysql import desc_mysql_fields, show_tables
from utils.hash import md5
from utils.tools import is_blank, process_error
from fastapi import APIRouter, Header, Depends
from pydantic import BaseModel
from models.requests import DataSourceRequest, TableInfoRequest
from components.db import prisma
from fastapi_jwt_auth import AuthJWT


from prisma.errors import UniqueViolationError
from fastapi_jwt_auth.exceptions import MissingTokenError, JWTDecodeError

from utils.resp import BusinessException, resp_err, resp_json, resp_ok, resp_data
from utils.time import current_datetime

ds_router = APIRouter()


@ds_router.post("/ds")
async def ds_list(item: DataSourceRequest):
# async def ds_list(item: UserAdd, Authorize: AuthJWT = Depends()):
    try:
        # show_tables(host="127.0.0.1", user="root", password="root", db="test", table_name="test")
        tables = show_tables(host=item.host, user=item.username, password=item.password, db=item.db, port=item.port)

        res = []
        for table in tables:
            tab  = {}
            tab["tableName"] = table
            fields = desc_mysql_fields(host=item.host, user=item.username, password=item.password, db=item.db, port=item.port, table_name=table)
            tab["fields"] = fields

            res.append(tab)

        return resp_data(res)
    except Exception as e:
        process_error(e)



@ds_router.get("/tableInfo")
async def tableInfo(item: TableInfoRequest):
# async def tableInfo(Authorize: AuthJWT = Depends()):
    try:
        # Authorize.jwt_required()

        # res = desc_mysql_fields(host="127.0.0.1", user="root", password="root", db="test", table_name="test")
        res = desc_mysql_fields(host=item.host, user=item.username, password=item.password, db=item.db, port=item.port, table_name=item.table)
        return resp_data(res)
    except Exception as e:
        process_error(e)
